/*
 * JaCoLiB
 * Copyright (C) 2008 Alessandro Serra
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

package it.gashale.jacolib.shell;

import it.gashale.jacolib.core.JacolibError;
import it.gashale.jacolib.rpc.RPCMethodHandler;
import it.gashale.jacolib.rpc.RPCRequest;
import it.gashale.jacolib.rpc.RPCServer;

public class ShellServer extends RPCServer {
	protected ShellInterface shell;
	protected RemoteShell callback_shell;
	
	public ShellServer(ShellInterface shell, RemoteShell cbshell) throws JacolibError {
		super();
		this.shell=shell;
		callback_shell=cbshell;
		init();
	}
	
	public void setCallbackShell(RemoteShell cbs) {
		callback_shell=cbs;
	}
	
	protected void init() {
		register("shell-hello",new RPCMethodHandler() {
			public Object safe_handles(RPCRequest req) throws JacolibError {
				return shell.hello();
			}
		});
		register("shell-language-name",new RPCMethodHandler() {
			public Object safe_handles(RPCRequest req) throws JacolibError {
				return shell.getLanguageName();
			}
		});
		register("shell-get",new RPCMethodHandler() {
			public Object safe_handles(RPCRequest req) throws JacolibError {
				return shell.get((String)arg(req,0));
			}
		});
		register("shell-unset",new RPCMethodHandler() {
			public Object safe_handles(RPCRequest req) throws JacolibError {
				shell.unset((String)arg(req,0));
				return null;
			}
		});
		register("shell-set",new RPCMethodHandler() {
			public Object safe_handles(RPCRequest req) throws JacolibError {
				shell.set((String)arg(req,0),arg(req,1));
				return null;
			}
		});
		register("shell-eval",new RPCMethodHandler() {
			public Object safe_handles(RPCRequest req) throws JacolibError {
				shell.set("callback_shell", callback_shell);
				Object o=shell.eval((String)arg(req,0));
				shell.set("callback_shell", null);
				return o; 
			}
		});
		register("shell-source",new RPCMethodHandler() {
			public Object safe_handles(RPCRequest req) throws JacolibError {
				shell.set("callback_shell", callback_shell);
				Object o=shell.source((String)arg(req,0));
				shell.set("callback_shell", null);
				return o;
			}
		});
	}
	/*
	 * quit
	 */
	protected void quit_p() {
		super.quit_p();
		shell=null;
		callback_shell=null;
	}
}
